package com.onemile.app;

import java.util.ArrayList;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.onemile.app.base.BaseUINoBottom;
import com.onemile.app.base.BaseUINoTopNoBottom;
import com.onemile.controls.AdpCstLV_Attribute;
import com.onemile.controls.CstLayoutListView;
import com.onemile.data.DXml;
import com.onemile.data.DXml.FieldList;
import com.onemile.entity.PubConst;
import com.onemile.entity.Session;
import com.onemile.entity.model.EAttribute;
import com.onemile.entity.model.EAttributeDetails;
import com.onemile.entity.model.ECommodity;
import com.onemile.entity.model.ECommodityAccessories;
import com.onemile.entity.model.ECommodityForCommit;
import com.onemile.entity.model.ESpecification;
import com.onemile.net.NetClient;
import com.onemile.utils.UtiDialogsFactory;

public class UICommodityList_Select extends BaseUINoBottom
{
   private String commodityId;
   private ECommodityForCommit commodity;

   private LayoutInflater mInflater;
   private TextView txtSpecification;
   private CstLayoutListView listAttribute;
   private TextView txtAccessories;

   private ImageView imgOK;
   private ImageView imgReturn;

   private EditText edtNum;
   private ImageView imgJia;
   private ImageView imgJian;

   private void InitControls()
   {
	  mInflater = LayoutInflater.from(this);
	  edtNum = (EditText) findViewById(R.id.edtNum_commodity_item_select);
	  listAttribute = (CstLayoutListView) findViewById(R.id.cstList_commodity_item_select);

	  txtSpecification = (TextView) findViewById(R.id.txtSpecification_commodity_item_select);
	  txtSpecification.setOnClickListener(new View.OnClickListener()
	  {
		 @Override
		 public void onClick(View v)
		 {
			UtiDialogsFactory.getInstance().ShowSingleSelectItemDialog(UICommodityList_Select.this, commodity.getSpecificationList(), null, new UtiDialogsFactory.DialogCallBack()
			{
			   @Override
			   public void SingleSelectDialogItemClick(ListView listView, View currentView, int position)
			   {
				  txtSpecification.setText(((ESpecification) listView.getAdapter().getItem(position)).getSpecificationName());
				  txtSpecification.setTag(listView.getAdapter().getItem(position));
			   }

			   @Override
			   public void MultiSelectDialogOKClick(ListView listView, ArrayList<Integer> selectList, int count)
			   {
			   }
			});
		 }
	  });
	  txtAccessories = (TextView) findViewById(R.id.txtAccessories_commodity_item_select);
	  txtAccessories.setOnClickListener(new View.OnClickListener()
	  {
		 @SuppressWarnings("unchecked")
		 @Override
		 public void onClick(View v)
		 {
			UtiDialogsFactory.getInstance().ShowMultiSelectItemDialog(UICommodityList_Select.this, commodity.getCommodityAccessoriesList(), (ArrayList<Integer>) txtAccessories.getTag(), null,
				  new UtiDialogsFactory.DialogCallBack()
				  {
					 @Override
					 public void SingleSelectDialogItemClick(ListView listView, View currentView, int position)
					 {
					 }

					 @Override
					 public void MultiSelectDialogOKClick(ListView listView, ArrayList<Integer> selectList, int count)
					 {
						if (count == 0)
						{
						   txtAccessories.setText(getString(R.string.all_plase_select));
						}
						else
						{
						   StringBuffer sb = new StringBuffer();
						   for (int i = 0; i < count; i++)
						   {
							  sb.append(commodity.getCommodityAccessoriesList().get(selectList.get(i)).getCommodityAccessoriesName());
							  sb.append(",");
						   }
						   txtAccessories.setText(sb.substring(0, sb.length() - 1));
						}
						txtAccessories.setTag(selectList);
					 }
				  });
		 }
	  });

	  imgJia = (ImageView) findViewById(R.id.imgJia_commodity_item_select);
	  imgJia.setOnClickListener(new View.OnClickListener()
	  {
		 @Override
		 public void onClick(View v)
		 {
			int num;
			if (edtNum.getText().toString() == null || edtNum.getText().toString().equals(""))
			{
			   num = 0;
			}
			else
			{
			   num = Integer.valueOf(edtNum.getText().toString());
			}
			num++;
			edtNum.setText(String.valueOf(num));
		 }
	  });
	  imgJian = (ImageView) findViewById(R.id.imgJian_commodity_item_select);
	  imgJian.setOnClickListener(new View.OnClickListener()
	  {
		 @Override
		 public void onClick(View v)
		 {
			int num;
			if (edtNum.getText().toString() == null || edtNum.getText().toString().equals(""))
			{
			   num = 0;
			}
			else
			{
			   num = Integer.valueOf(edtNum.getText().toString());
			}
			num--;
			edtNum.setText(String.valueOf(num));
		 }
	  });
	  imgOK = (ImageView) findViewById(R.id.imgOK_commodity_item_select);
	  imgOK.setOnClickListener(new View.OnClickListener()
	  {
		 @Override
		 public void onClick(View v)
		 {
			try
			{
			   if(VerifyInfo())
			   {
				  ECommodity ec = new ECommodity();
				   ec.setCommodityName(commodity.getCommodityName());
				   ec.setCommodityId(commodity.getCommodityId());
				   ec.setShopsId(commodity.getShopsId());
				   ec.setIsHot(commodity.isIsHot());
				   ec.setIsNew(commodity.isIsNew());
				   ec.setCount(Integer.valueOf(edtNum.getText().toString().trim()));
				   ec.setSpecification((ESpecification) txtSpecification.getTag());
				   ec.setAttributeDetailsList(((AdpCstLV_Attribute) listAttribute.getAdpater()).getSelectAttributeDetails());
	               
				   float totalPrice=((ESpecification) txtSpecification.getTag()).getPrice();
				   ArrayList<ECommodityAccessories> list = new ArrayList<ECommodityAccessories>();
				   ArrayList<Integer> selectList = (ArrayList<Integer>) txtAccessories.getTag();// 选中的附件的index列表
				   int size = selectList.size();// 选中了几个
				   for (int i = 0; i < size; i++)
				   {
					  ECommodityAccessories eca=commodity.getCommodityAccessoriesList().get(selectList.get(i));
					  totalPrice=totalPrice + Float.valueOf(eca.getCommodityAccessoriesPrice());
					  list.add(eca);
				   }
				   ec.setCommodityAccessoriesList(list);
				   ec.setPrice(totalPrice*ec.getCount());
				   
				   Session.getInstance().AddCommodity(ec);
				   UtiDialogsFactory.getInstance().ShowCustomButtonAlertDialog(UICommodityList_Select.this, getString(R.string.dialog_tips), getString(R.string.dialog_add_success),
						 getString(R.string.dialog_go_settle), new DialogInterface.OnClickListener()
						 {
							@Override
							public void onClick(DialogInterface dialog, int which)
							{
							   Intent intent = new Intent();
							   intent.setClass(UICommodityList_Select.this, UICart.class);
							   startActivity(intent);
							   finish();
							}
						 }, 
						 getString(R.string.dialog_goon_buy), new DialogInterface.OnClickListener()
						 {
							@Override
							public void onClick(DialogInterface dialog, int which)
							{
							   finish();
							}
						 }); 
			   }
			}
			catch (Exception e)
			{
			   UtiDialogsFactory.getInstance().ShowToastInfoShort(UICommodityList_Select.this, getString(R.string.dialog_uploading_failed));
			   if (Session.getInstance().IsDEBUG())
			   {
				  Log.e("ERROR", "UICommodityList_Select.InitControls().new OnClickListener() {...}_onClick(v) ", e);
			   }
			}
		 }
	  });
	  
	  imgReturn=(ImageView)findViewById(R.id.imgReturn_commodity_item_select);
	  imgReturn.setOnClickListener(new View.OnClickListener()
	  {
	     @Override
	     public void onClick(View v)
	     {
	  	   finish(); 
	     }
	  });
   }

   private boolean VerifyInfo()
   {
	  if (edtNum.getText().toString().trim() == null || edtNum.getText().toString().trim().equals(""))// 用户名为空
	  {
		 UtiDialogsFactory.getInstance().ShowToastInfoShort(UICommodityList_Select.this, getString(R.string.commodity_num_no_empty));
		 return false;
	  }	 
	  else if (txtSpecification.getTag()==null)// 规格为空
	  {
		 UtiDialogsFactory.getInstance().ShowToastInfoShort(UICommodityList_Select.this, getString(R.string.commodity_specification_no_empty));
		 return false;
	  }
	  else if (txtAccessories.getTag()==null)// 附件为空
	  {
		 UtiDialogsFactory.getInstance().ShowToastInfoShort(UICommodityList_Select.this, getString(R.string.commodity_accessories_no_empty));
		 return false;
	  }

	  return true;
   }
   
   @Override
   protected void onCreateOverride(Bundle savedInstanceState)
   {
	  try
	  {
		 commodityId = getIntent().getStringExtra(PubConst.Intent_Key.COMMODITY_ID);
		 InitControls();
		 executeAsyncTask(PubConst.TaskName.COMMODITY_LIST_SELECT);
	  }
	  catch (Exception e)
	  {
		 if (Session.getInstance().IsDEBUG())
		 {
			Log.e("ERROR", "UICommodityList_Select_onCreateOverride(savedInstanceState) ", e);
		 }
	  }

   }

   @Override
   public int SetContentViewLayoutResId()
   {
	  return R.layout.commoditylist_item_select_details;
   }

   @Override
   public void onAsyncTaskStart(String taskName, Object[] params)
   {
	  try
	  {
		 if (taskName.equals(PubConst.TaskName.COMMODITY_LIST_SELECT))
		 {
			UtiDialogsFactory.getInstance().ShowLoadingDialogNoTitle(UICommodityList_Select.this, getString(R.string.dialog_loading));
		 }
	  }
	  catch (Exception e)
	  {
		 if (Session.getInstance().IsDEBUG())
		 {
			Log.e("ERROR", "UICommodityList_Select_onAsyncTaskStart(taskName, params) ", e);
		 }
	  }
   }

   @Override
   public Object onAsyncTaskInBackground(String taskName, Object[] params) throws Exception
   {
	  try
	  {
		 if (taskName.equals(PubConst.TaskName.COMMODITY_LIST_SELECT))
		 {
			return NetClient.GetCommodityInfo(commodityId);
		 }
	  }
	  catch (Exception e)
	  {
		 if (Session.getInstance().IsDEBUG())
		 {
			Log.e("ERROR", "UICommodityList_Select_onAsyncTaskInBackground(taskName, params) ", e);
		 }
	  }
	  return null;
   }

   @Override
   public void onAsyncTaskEnd(String taskId, String taskName, Object[] params, Object result)
   {
	  try
	  {
		 if (taskName.equals(PubConst.TaskName.COMMODITY_LIST_SELECT))
		 {
			UtiDialogsFactory.getInstance().DismissLoadingDialog();
			if (result != null)
			{
			   DXml data = (DXml) result;
			   commodity = new ECommodityForCommit();
			   commodity.setCommodityId(data.getBody().GetFieldValue("CommodityId"));
			   commodity.setCommodityName(data.getBody().GetFieldValue("CommodityName"));
			   commodity.setIsHot(data.getBody().GetFieldInt32("IsHot") == 1 ? true : false);
			   commodity.setIsNew(data.getBody().GetFieldInt32("IsNew") == 1 ? true : false);
               commodity.setShopsId(data.getBody().GetFieldValue("ShopsId"));
			   
               // 规格列表
			   ArrayList<ESpecification> listS = new ArrayList<ESpecification>();
			   ESpecification es = null;
			   FieldList sList = data.getBody().GetFieldList("SpecificationList");
			   int sizeS = sList.getChilds().length;
			   for (int i = 0; i < sizeS; i++)
			   {
				  FieldList ssList = sList.GetFieldList(i);
				  es = new ESpecification();
				  es.setCommodityPriceId(ssList.GetFieldValue("CommodityPriceId"));
				  es.setDescription(ssList.GetFieldValue("Desription"));
				  es.setSpecificationId(ssList.GetFieldValue("SpecificationId"));
				  es.setSpecificationName(ssList.GetFieldValue("SpecificationName"));
				  es.setPrice(Float.valueOf(ssList.GetFieldValue("Price")));
				  es.setHigh(ssList.GetFieldValue("High"));
				  es.setLong(ssList.GetFieldValue("Long"));
				  es.setWeight(ssList.GetFieldValue("Weight"));
				  es.setWide(ssList.GetFieldValue("Wide"));
				  listS.add(es);
			   }
			   // 附件列表
			   ArrayList<ECommodityAccessories> listC = new ArrayList<ECommodityAccessories>();
			   ECommodityAccessories eca = null;
			   FieldList cList = data.getBody().GetFieldList("CommodityAccessoriesList");
			   int sizeC = cList.getChilds().length;
			   for (int i = 0; i < sizeC; i++)
			   {
				  FieldList ccList = cList.GetFieldList(i);
				  eca = new ECommodityAccessories();
				  eca.setCommodityAccessoriesId(ccList.GetFieldValue("CommodityAccessoriesId"));
				  eca.setCommodityAccessoriesName(ccList.GetFieldValue("CommodityAccessoriesName"));
				  eca.setCommodityAccessoriesPrice(ccList.GetFieldValue("CommodityAccessoriesPrice"));
				  listC.add(eca);
			   }
			   // 属性列表
			   ArrayList<EAttribute> listA = new ArrayList<EAttribute>();
			   EAttribute ea = null;
			   FieldList aList = data.getBody().GetFieldList("AttributeList");
			   int sizeA = aList.getChilds().length;
			   for (int i = 0; i < sizeA; i++)
			   {
				  FieldList aaList = aList.GetFieldList(i);
				  ea = new EAttribute();
				  ea.setAttributeId(aaList.GetFieldValue("AttributeId"));
				  ea.setAttributeName(aaList.GetFieldValue("AttributeName"));
				  ea.setDescription(aaList.GetFieldValue("Description"));
				  // 属性详情列表
				  ArrayList<EAttributeDetails> listAD = new ArrayList<EAttributeDetails>();
				  EAttributeDetails ead = null;
				  FieldList adList = aaList.GetFieldList("AttributeDetailsList");
				  int sizeAD = adList.getChilds().length;
				  for (int j = 0; j < sizeAD; j++)
				  {
					 FieldList aadList = adList.GetFieldList(j);
					 ead = new EAttributeDetails();
					 ead.setAttributeDetailsId(aadList.GetFieldValue("AttributeDetailsId"));
					 ead.setAttributeDetailsName(aadList.GetFieldValue("AttributeDetailsName"));
					 listAD.add(ead);
				  }
				  ea.setAttributeDetailsList(listAD);

				  listA.add(ea);
			   }

			   commodity.setSpecificationList(listS);
			   commodity.setCommodityAccessoriesList(listC);
			   commodity.setAttributeList(listA);

			   AdpCstLV_Attribute adpAttr = new AdpCstLV_Attribute(listA, UICommodityList_Select.this);
			   listAttribute.setAdapter(adpAttr);

			}
		 }
	  }
	  catch (Exception e)
	  {
		 if (Session.getInstance().IsDEBUG())
		 {
			Log.e("ERROR", "UICommodityList_Select_onAsyncTaskEnd(taskId, taskName, params, result) ", e);
		 }
	  }
   }

   @Override
   public void SetTopToolbar(TextView topTxt, ImageView leftImBtn, ImageView rightImgBtn, RelativeLayout rightRay, TextView cartNum)
   {
      topTxt.setText(getString(R.string.title_commodityselect));
	  
   }

}
